<template>
  <div class="tasks">
    <header class="tasks-header">
      <h1>我的待办事项</h1>
      <button class="btn btn-logout" @click="handleLogout">退出登录</button>
    </header>
    
    <div v-if="loading" class="loading">正在加载任务...</div>
    <div v-if="error" class="error-message">{{ error }}</div>
    
    <!-- Task creation form -->
    <div class="task-form">
      <h2>添加新任务</h2>
      <form @submit.prevent="handleAddTask">
        <div class="form-group">
          <label for="title">标题</label>
          <input 
            type="text" 
            id="title" 
            v-model="newTask.title" 
            required
            placeholder="请输入任务标题"
          >
        </div>
        
        <div class="form-group">
          <label for="description">描述</label>
          <textarea 
            id="description" 
            v-model="newTask.description" 
            placeholder="请输入任务描述"
            rows="3"
          ></textarea>
        </div>
        
        <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
          {{ isSubmitting ? '添加中...' : '添加任务' }}
        </button>
      </form>
    </div>
    
    <!-- Task list -->
    <div class="task-list" v-if="tasks.length > 0">
      <h2>你的任务列表</h2>
      <div 
        v-for="task in tasks" 
        :key="task.id" 
        class="task-item"
        :class="{'task-completed': task.status === 'completed'}"
      >
        <div class="task-content">
          <h3 class="task-title">{{ task.title }}</h3>
          <p class="task-description">{{ task.description }}</p>
          <p class="task-date">创建时间: {{ new Date(task.created_at).toLocaleString() }}</p>
        </div>
        
        <div class="task-actions">
          <button 
            class="btn btn-status" 
            @click="toggleTaskStatus(task)"
            :class="task.status === 'completed' ? 'btn-incomplete' : 'btn-complete'"
          >
            {{ task.status === 'completed' ? '标记为未完成' : '标记为已完成' }}
          </button>
          <button class="btn btn-danger" @click="deleteTask(task.id)">删除</button>
        </div>
      </div>
    </div>
    
    <div v-else-if="!loading" class="no-tasks">
      <p>你还没有任何任务，请在上方添加！</p>
    </div>
  </div>
</template>

<script>
import api from '../services/api'

export default {
  name: 'TasksView',
  data() {
    return {
      tasks: [],
      loading: false,
      error: null,
      isSubmitting: false,
      newTask: {
        title: '',
        description: ''
      }
    }
  },
  created() {
    this.fetchTasks()
  },
  methods: {
    async fetchTasks() {
      this.loading = true
      this.error = null
      
      try {
        const response = await api.getTasks()
        this.tasks = response.data
      } catch (err) {
        console.error('Error fetching tasks:', err)
        this.error = '加载任务失败，请重试'
        
        // If unauthorized, redirect to login
        if (err.response?.status === 401) {
          localStorage.removeItem('token')
          this.$router.push('/login')
        }
      } finally {
        this.loading = false
      }
    },
    
    async handleAddTask() {
      this.isSubmitting = true
      
      try {
        const response = await api.createTask(this.newTask)
        this.tasks.unshift(response.data)
        
        // Reset form
        this.newTask.title = ''
        this.newTask.description = ''
      } catch (err) {
        console.error('Error adding task:', err)
        this.error = '添加任务失败，请重试'
      } finally {
        this.isSubmitting = false
      }
    },
    
    async toggleTaskStatus(task) {
      try {
        const updatedTask = {
          ...task,
          status: task.status === 'completed' ? 'pending' : 'completed'
        }
        
        const response = await api.updateTask(task.id, updatedTask)
        
        // Update task in the list
        const index = this.tasks.findIndex(t => t.id === task.id)
        if (index !== -1) {
          this.tasks.splice(index, 1, response.data)
        }
      } catch (err) {
        console.error('Error updating task:', err)
        this.error = '更新任务失败，请重试'
      }
    },
    
    async deleteTask(taskId) {
      if (!confirm('确定要删除此任务吗？')) {
        return
      }
      
      try {
        await api.deleteTask(taskId)
        
        // Remove task from the list
        this.tasks = this.tasks.filter(task => task.id !== taskId)
      } catch (err) {
        console.error('Error deleting task:', err)
        this.error = '删除任务失败，请重试'
      }
    },
    
    handleLogout() {
      localStorage.removeItem('token')
      this.$router.push('/login')
    }
  }
}
</script>

<style scoped>
.tasks {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
}

.tasks-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

h1 {
  color: #2c3e50;
  margin: 0;
}

h2 {
  color: #2c3e50;
  margin-bottom: 1rem;
}

.loading {
  text-align: center;
  margin: 2rem 0;
  color: #2c3e50;
  font-style: italic;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding: 0.75rem;
  margin-bottom: 1.5rem;
  border-radius: 4px;
  text-align: center;
}

.btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.btn-primary {
  background-color: #42b983;
  color: white;
  width: 100%;
  padding: 0.75rem;
}

.btn-primary:hover:not(:disabled) {
  background-color: #3aa876;
}

.btn-logout {
  background-color: #dc3545;
  color: white;
}

.btn-logout:hover {
  background-color: #c82333;
}

.btn-status {
  background-color: #17a2b8;
  color: white;
  margin-right: 0.5rem;
}

.btn-complete:hover {
  background-color: #138496;
}

.btn-incomplete {
  background-color: #6c757d;
}

.btn-incomplete:hover {
  background-color: #5a6268;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover {
  background-color: #c82333;
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.task-form {
  background-color: #f8f9fa;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 2rem;
}

.form-group {
  margin-bottom: 1.2rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
  color: #2c3e50;
}

input, textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

input:focus, textarea:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
}

.task-list {
  margin-top: 2rem;
}

.task-item {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 1rem;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.task-completed {
  background-color: #e8f5e9;
}

.task-completed .task-title {
  text-decoration: line-through;
  color: #7c7c7c;
}

.task-title {
  margin: 0 0 0.5rem;
  color: #2c3e50;
}

.task-description {
  margin: 0 0 0.5rem;
  color: #546e7a;
}

.task-date {
  font-size: 0.85rem;
  color: #7c7c7c;
  margin: 0 0 1rem;
}

.task-actions {
  display: flex;
  justify-content: flex-start;
  margin-top: 1rem;
}

.no-tasks {
  text-align: center;
  color: #7c7c7c;
  font-style: italic;
  margin-top: 2rem;
}
</style> 